import React, { lazy, Suspense } from "react";
import { Navigate, useRoutes } from "react-router-dom";
import { Spin } from "antd";

// 懒加载组件
const Login = lazy(() => import("@/pages/sso/Login"));
const Register = lazy(() => import("@/pages/sso/Register"));
const Dashboard = lazy(() => import("@/pages/Dashboard"));
const UserManagement = lazy(() => import("@/pages/user/UserManagement"));
const NotFound = lazy(() => import("@/pages/NotFound"));

// 路由守卫组件
const AuthGuard: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const token = localStorage.getItem("token");
  if (!token) {
    return <Navigate to="/login" replace />;
  }
  return <>{children}</>;
};

// 懒加载包装器
const LazyWrapper: React.FC<{ component: React.ReactNode }> = ({
  component,
}) => (
  <Suspense
    fallback={
      <Spin
        size="large"
        className="flex justify-center items-center h-screen"
      />
    }
  >
    {component}
  </Suspense>
);

const Routes: React.FC = () => {
  return useRoutes([
    {
      path: "/",
      element: <Navigate to="/dashboard" replace />,
    },
    {
      path: "/login",
      element: <LazyWrapper component={<Login />} />,
    },
    {
      path: "/register",
      element: <LazyWrapper component={<Register />} />,
    },
    {
      path: "/dashboard",
      element: (
        <AuthGuard>
          <LazyWrapper component={<Dashboard />} />
        </AuthGuard>
      ),
    },
    {
      path: "/user",
      children: [
        {
          path: "management",
          element: (
            <AuthGuard>
              <LazyWrapper component={<UserManagement />} />
            </AuthGuard>
          ),
        },
      ],
    },
    {
      path: "*",
      element: <LazyWrapper component={<NotFound />} />,
    },
  ]);
};

export default Routes;
